// pages/phoneNumberLogin/phoneNumberLogin.js
const app = getApp();
import request from "../../utils/request";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    errorMessage: "",
    code: null,
    phoneNumber: null,
    countdown: 60, //初始设为60秒
    disabled: false,
    phone: "",
    messageCode: null,
    sms: "",
    title: "手机号登录",
    buttonName: "立即登录",
    Message: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    if (options.title == "修改手机号") {
      this.setData({
        title: "修改手机号",
        buttonName: "保存设置",
      });
    }
  },
  goback() {
    wx.navigateBack({
      delta: 1,
    });
  },
  errorMessage(e) {
    const value = e.detail.value;
    this.setData({
      phone: value,
    });
  },
  msgCode(e) {
    const value = e.detail.value;
    this.setData({
      sms: value,
    });
    this.verificationCode();
  },
  getCode() {
    const phoneRegex = /^1[3-9]\d{9}$/; //匹配中国大陆手机号码
    if (!phoneRegex.test(this.data.phone)) {
      this.setData({
        errorMessage: "请输入有效的电话号码",
      });
      wx.showToast({
        title: this.data.errorMessage,
        icon: "none",
        duration: 2000,
      });
    } else {
      // 如果输入的内容是有效的电话号码，清空错误信息,这里可以放发送短息验证码的方法，然后去调用这个方法
      this.setData({
        errorMessage: "",
      });
      this.getCodeMessage();
      this.startCountdown();
    }
  },
  startCountdown: function () {
    let that = this;
    that.setData({
      disabled: true,
    });
    const interval = setInterval(() => {
      that.setData({
        countdown: that.data.countdown - 1, // 减少时间
      });
      if (that.data.countdown === 0) {
        clearInterval(interval); // 清除定时器
        that.setData({
          countdown: 60, // 重置倒计时
          disabled: false,
        });
      }
    }, 1000);
  },
  getCodeMessage() {
    wx.request({
      url: app.globalData.baseURL + "/app-user-api/member/auth/send-sms-code",
      method: "POST",
      header: {
        "tenant-id": "156",
        "Authorization": "Bearer test1",
        "login_user_type":3
      },
      data: {
        mobile: this.data.phone,
        scene: 1,
      },
      success: (res) => {
        console.log(res);
      },
    });
  },
  verificationCode() {
    wx.request({
      url:
        app.globalData.baseURL + "/app-user-api/member/auth/validate-sms-code",
      method: "POST",
      header: {
        "tenant-id": "156",
        "Authorization": "Bearer test1",
        "login_user_type":3
      },
      data: {
        mobile: this.data.phone,
        scene: 1,
        code: this.data.sms,
      },
      success: (res) => {
        console.log(res);
      },
    });
  },
  async goLogin() {
    const scene = wx.getStorageSync('scene')
    if(scene !== ''){
      const data  = {
        mobile: this.data.phone,
        code: this.data.sms,
        shareUserId:scene
      }
      this.login(data)
    }else{
      const data  = {
        mobile: this.data.phone,
        code: this.data.sms
      }
      this.login(data)
    }
  },
 async login(data){
    if (this.data.title == "手机号登录") {
      wx.request({
        url: app.globalData.baseURL + "/app-user-api/member/auth/sms-login",
        method: "POST",
        header: {
          "tenant-id": "156",
          "login_user_type":3
        },
        data: data,
        success: (res) => {
          if (res.data.code === 0) {
            wx.switchTab({
              url: "../index/index",
            });
            wx.showToast({
              title: "登录成功",
              icon: "success",
            });
          }
          const token = res.data.data.accessToken;
          wx.setStorageSync("token", token);
          wx.setStorageSync("expiresTime", res.data.data.expiresTime);
          wx.setStorageSync("refreshToken", res.data.data.refreshToken);
          wx.setStorageSync("userId", res.data.data.userId);
          wx.setStorageSync('openid', res.data.data.openid)
          const newMemberId = res.data.data.userId
          this.shareUserCreat(newMemberId)
        },
      });
    } else {
      try {
        const res = await request({
          url:
            app.globalData.baseURL + "/app-user-api/member/user/update-mobile",
          method: "PUT",
          data: data,
        });
        this.setData({
          Message: res.msg,
        });
        if (res.code == 0) {
          wx.showToast({
            title: "修改手机号成功",
            icon: 'success',
          });
        }else{
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration:2000 
          })
        }
      } catch {
        wx.showToast({
          title: this.data.Message
        });
      }
    }
  },
  async shareUserCreat(newMemberId){
    const scene = wx.getStorageSync('scene')
    const res = await request({
      url: app.globalData.baseURL + '/app-user-api/member/share-user/create',
      method:'POST',
      data:{
       memberId:scene,
       newMemberId:newMemberId
      }
    })
    console.log(res);
 },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    return {
      title: "嘉之勤官网小程序",
      path: "/pages/index/index",
      imageUrl:
        "https://youyougo2.oss-cn-chengdu.aliyuncs.com/0201506f6fc0f4145e34159c2e2ac66b94b96450dd29e5a19d177edc5dad8023.png",
    };
  },
});
